package com.shwread.httpsdk.http.base;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.HashMap;

import logic.constants.Const;
import logic.util.FileUtil;

import org.apache.http.HttpHost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;

import android.content.Context;
import android.os.Looper;

import com.shwread.httpsdk.http.base.proxy.ProxyConsts;
import com.shwread.httpsdk.http.base.ui.AbstractHttpUiUtil;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.util.Base64;
import com.shwread.httpsdk.util.NetUtil;
import com.shwread.httpsdk.util.Util;


/**
 * @author 刘章
 * @Title: AbstractHttpBase.java
 * @Package com.surfingread.httpsdk.http.base
 * @Description: TODO(添加描述)
 * @date 2014年1月22日 下午1:09:31
 */
public abstract class AbstractHttpBase extends Thread {
    public static final int CONNECTION_TIMEOUT = 15 * 1000;
    public static final int SO_TIMEOUT = 15 * 1000;
    //设置代理
    protected static HttpHost proxy = new HttpHost(ProxyConsts.Proxy_ip, ProxyConsts.Proxy_port);
    // 设置代理:
    protected static HttpHost ct_proxy = new HttpHost("10.0.0.200", 80);
    protected static HttpHost cm_proxy = new HttpHost("10.0.0.172", 80);
    protected static HttpHost uni_proxy = new HttpHost("10.0.0.172", 80);

    protected static HttpParams params = new BasicHttpParams();

    private boolean showSysNetErrorToast = false;

    static {
        //连接超时
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
        //请求超时
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
    }

    protected abstract void doHttp();

    protected abstract void doRequestHeader(HashMap<String, String> header_map);

    public abstract void dispose();

    public HashMap<String, String> header_map = new HashMap<>();

    protected ActionListener listener;

    protected Context context;
    private String action;

    public AbstractHttpBase(Context mContext, String action, ActionListener actionListener) {
        context = mContext;
        this.action = action;
        if (Util.isNotEmpty(action)) {
            header_map.put("Action", action);
        }
        listener = actionListener;
    }

    protected void InitProxy() {
        if (NetUtil.isChinaTelecom(context) == NetUtil.IS_CT && NetUtil.getNetType(context) == NetUtil.CURRENT_NETWORK_TYPE_CTWAP) {
            //中国电信 制式下 ctwap网络
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY, ct_proxy);
        }
        /*
         * else if (NetUtil.isChinaTelecom(context) == NetUtil.IS_CM &&
		 * NetUtil.getNetType(context) == NetUtil.CURRENT_NETWORK_TYPE_CMWAP)
		 * {
		 * //中国移动 制式下 cmwap网络
		 * params.setParameter(ConnRoutePNames.DEFAULT_PROXY, cm_proxy);
		 * }
		 * else if (NetUtil.isChinaTelecom(context) == NetUtil.IS_UNI &&
		 * NetUtil.getNetType(context) == NetUtil.CURRENT_NETWORK_TYPE_UNIWAP)
		 * {
		 * //中国联通 制式下 uniwap网络
		 * params.setParameter(ConnRoutePNames.DEFAULT_PROXY, uni_proxy);
		 * }
		 */
        else {
            params.removeParameter(ConnRoutePNames.DEFAULT_PROXY);
        }
    }

    protected void InitProxy1() {
        if (NetUtil.isChinaTelecom(context) == NetUtil.IS_CT && NetUtil.getNetType(context) == NetUtil.CURRENT_NETWORK_TYPE_CTWAP) {
            //中国电信 制式下 ctwap网络
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            header_map.put("ab_pid", Base64.encode(ProxyConsts.appId, "UTF-8"));
            header_map.put("ab_uid", Base64.encode(ProxyConsts.userId, "UTF-8"));
        } else if (NetUtil.isChinaTelecom(context) == NetUtil.IS_CM && NetUtil.getNetType(context) == NetUtil.CURRENT_NETWORK_TYPE_CMWAP) {
            //中国移动 制式下 cmwap网络
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            header_map.put("ab_pid", Base64.encode(ProxyConsts.appId, "UTF-8"));
            header_map.put("ab_uid", Base64.encode(ProxyConsts.userId, "UTF-8"));
        } else if (NetUtil.isChinaTelecom(context) == NetUtil.IS_UNI && NetUtil.getNetType(context) == NetUtil.CURRENT_NETWORK_TYPE_UNIWAP) {
            //中国联通 制式下 uniwap网络
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            header_map.put("ab_pid", Base64.encode(ProxyConsts.appId, "UTF-8"));
            header_map.put("ab_uid", Base64.encode(ProxyConsts.userId, "UTF-8"));
        } else {
            params.removeParameter(ConnRoutePNames.DEFAULT_PROXY);
        }
    }

    public HashMap<String, String> getHeader() {
        header_map.put("Connection", "Keep-Alive");
        header_map.put("Chartset", Const.charset);
        header_map.put("Cache-Control", "no-cache");
        header_map.put("Accept-Language", "zh-CN,en-US");

        header_map.put("Content-Type", Const.ContentType);
        header_map.put("client-imei", NetUtil.getImei(context));
        header_map.put("user-ip", NetUtil.getPsdnIp());
        if (Util.isNotEmpty(Const.phone_number)) {
            header_map.put("phone-number", Const.phone_number);
        } else {
            //#debug
            System.err.println("error action=" + header_map.get("Action") + " | phone number =" + Const.phone_number);
        }
        doRequestHeader(header_map);
        return header_map;
    }

    public String clientHash(String value) {
        try {
            return "EhzDqBldJxQew68Kw6VITXDCkg8=";
            //return BASE64.base64Encode(MD5.MD5Encode(ActionConstant.clientVersion + value  + ActionConstant.clientKey).getBytes(ActionConstant.charset));
        } catch (Exception e) {
            return "";
        }
    }

    public static String convertStreamToString(InputStream in) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
        for (String line = r.readLine(); line != null; line = r.readLine()) {
            sb.append(line);
        }
        in.close();
        return sb.toString();
    }

    @Override
    public void run() {
        Looper.prepare();
        if (NetUtil.isNetworkConnected(context)) {
            InitProxy();
            doHttp();
        } else {
            HTTPERROR(NetUtil.NetNotConnectioned, null);
        }
    }

    public void cancelShowSysNetErrorToast() {
        showSysNetErrorToast = false;
    }

    protected void HTTPERROR(int statusCode, Throwable throwable) {
        if (throwable != null) {
            if (throwable instanceof ConnectTimeoutException) {
                statusCode = NetUtil.NetTimeOut;
            } else if (throwable instanceof SocketTimeoutException) {
                statusCode = NetUtil.NetTimeOut;
            } else if (throwable instanceof SocketException) {
                statusCode = NetUtil.NetResetByPeer;
            }
            //#debug
            throwable.printStackTrace();
            System.err.println("---(" + statusCode + ")--" + throwable.getMessage() + "--");
        }
        if (showSysNetErrorToast) AbstractHttpUiUtil.showToast(context, statusCode);
        if (listener != null) listener.HTTPERROR(statusCode);
    }

    public void println(String value) {
        //#debug
        System.out.println(context.getClass().getSimpleName() + " --> " + action + ":" + value);
        //LogUtil.d("HTTP", value);
    }

    public boolean writeOnlineXML(String contentId, String chapterId, String xml) {
        return FileUtil.writeOnlineXML(contentId, chapterId, xml);
    }
}
